﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace InterpreterPattern
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("这是20234710 钟培城的解释器模式");
            //定义一个英文的句子
            string english = "This is an apple.This is an apple.This is an apple.";
            //定义字符串变量 保存解释之后的句子
            StringBuilder sb = new StringBuilder();
            //定义集合数据  保存要解释的表达式
            List<IExpression> expressions = new List<IExpression>();

            //解释的过程
            //第一次分割是拆成句子
            string[] elements = english.Split(new char[] { '.' },
                StringSplitOptions.RemoveEmptyEntries);
            foreach (string element in elements)
            {
                //第二次分割是拆成单词
                string[] words = element.Split(new char[] { ' ' },
                    StringSplitOptions.RemoveEmptyEntries);
                foreach (string word in words)
                {
                    expressions.Add(new WordExpression(word));
                }
                expressions.Add(new SymbolExpression("."));
            }
            //完成解释，组合
            foreach (IExpression expression in expressions)
            {
                expression.Interpret(sb);
            }

            Console.WriteLine($"英文句子  {english}  解释之后为：");
            Console.WriteLine(sb);
            Console.ReadKey();
        }
    }
    //抽象表达式
    interface IExpression
    {
        void Interpret(StringBuilder sb);
    }

    //终结符表达式  标点符号的解释
    class SymbolExpression : IExpression
    {
        private string symbol;
        public SymbolExpression(string symbol)
        {
            this.symbol = symbol;
        }
        public void Interpret(StringBuilder sb)
        {
            if (symbol == ".")
            {
                sb.Append("。");
            }
        }
    }

    //非终结符表达式  英文单词的解释
    class WordExpression : IExpression
    {
        private string word;
        public WordExpression(string word)
        {
            this.word = word;
        }
        public void Interpret(StringBuilder sb)
        {
            sb.Append(ChineseEnglishDict.GetChinese(word.ToLower()));
        }
    }
    class ChineseEnglishDict
    {
        //字典数据，保存对应关系的文法规则
        private static Dictionary<string, string> dict = new Dictionary<string, string>();
        static ChineseEnglishDict()
        {
            dict.Add("this", "这");
            dict.Add("is", "是");
            dict.Add("an", "一个");
            dict.Add("apple", "苹果");
        }
        public static string GetChinese(string word)
        {
            return dict[word];
        }
    }
}
